package com.tupu.service.impl.dispatch;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tupu.entity.admin.TbFiles;
import com.tupu.mapper.dispatch.TbFilesMapper;
import com.tupu.service.dispatch.TbFilesService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class TbFilesServiceImpl implements TbFilesService {

    @Resource
    private TbFilesMapper tbFilesMapper;

    @Override
    public boolean insertTbFile(String fileName, String fileContent, String fileType) {
        TbFiles tbFiles = new TbFiles();
        String[] fileNames = fileName.split("\\.");
        if (fileNames.length != 2) {
            throw new RuntimeException("文件名不规范");
        }
        tbFiles.setFileName(fileName);
        tbFiles.setFileSuffix(fileNames[1]);
        tbFiles.setFileContent(fileContent);
        tbFiles.setInsertDate(new Date());
        return tbFilesMapper.insert(tbFiles) == 1;
    }

    @Override
    public TbFiles getTbFiles(String businessId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("business_id", businessId);
        queryWrapper.orderByDesc("insert_date");
        List<TbFiles> tbFilesList = tbFilesMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(tbFilesList)) {
            throw new RuntimeException("未找到文件！");
        }
        return tbFilesList.get(0);
    }

    @Override
    public boolean insertTbFileByFile(MultipartFile file, String businessId) {
        try {
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            String fileContent = Base64.encode(bytes);
            TbFiles tbFiles = new TbFiles();
            String[] fileNames = fileName.split("\\.");
            if (fileNames.length != 2) {
                throw new RuntimeException("文件名不规范");
            }
            tbFiles.setFileName(fileName);
            tbFiles.setFileSuffix(fileNames[1]);
            tbFiles.setFileContent(fileContent);
            tbFiles.setInsertDate(new Date());
            tbFiles.setBusinessId(businessId);
            return tbFilesMapper.insert(tbFiles) == 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存文件失败！" + e.getMessage());
        }
    }
}
